package com.yeyks.wxpay.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeyks.util.Utility;
import com.yeyks.wxpay.WXPay;
import com.yeyks.wxpay.WXPayConstants;
import com.yeyks.wxpay.WXPayUtil;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.yeyks.util.Utility;
import com.yeyks.wxpay.WXPay;
import com.yeyks.wxpay.WXPayConstants;
import com.yeyks.wxpay.WXPayUtil;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.yeyks.wxpay.WXPayConstants.FIELD_SIGNTYPE;

public class WXPayUtility {
    private final static String WXPAY_REFRESH_TOKEN = "wxpay_refresh_token";

    public static String extraInfo2refreshToken(String extraInfo) {
        return Utility.getExtraInfo(extraInfo, WXPAY_REFRESH_TOKEN);
    }

    public static String setRefreshTokenToExtraInfo(String extraInfo, String refreshToken) {
        return Utility.setExtraInfo(extraInfo, WXPAY_REFRESH_TOKEN, refreshToken);
    }

    public static String refreshToken2openId(String refreshToken) {
        String openid = null;

        try {
            MyConfig config = new MyConfig();
            String param = String.format(
                    "appid=%s&grant_type=refresh_token&refresh_token=%s",
                    config.getAppID(),
                    refreshToken);

            String response = Utility.sendGet("https://api.weixin.qq.com/sns/oauth2/refresh_token", param);

            JSONObject jsonObject = (JSONObject) JSON.parse(response);
            openid = jsonObject.get("openid").toString();
        } catch (Throwable e) {
            e.printStackTrace();

        }
        return openid;
    }
    public static String getOpenIdFromExtraInfo(String extraInfo) {
        return refreshToken2openId(extraInfo2refreshToken(extraInfo));
    }

    public static JSONObject code2Object(String code) {

        JSONObject jsonObject = null;

        try {
            MyConfig config = new MyConfig();
            String param = String.format(
                    "appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                    config.getAppID(), config.getSecret(), code);

            String response = Utility.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", param);

            jsonObject = (JSONObject) JSON.parse(response);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    public static String code2refreshToken(String code) {

        try {
            return code2Object(code).get("refresh_token").toString();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String code2openId(String code) {

        try {
            return code2Object(code).get("openid").toString();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String codeObject2refreshToken(JSONObject jsonObject) {

        try {
            return jsonObject.get("refresh_token").toString();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String codeObject2openId(JSONObject jsonObject) {

        try {
            return jsonObject.get("openid").toString();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, String> preOrder(String openId, String body, Long totalFee, Map<String, String> request) throws Exception {

        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);

        String orderNo = new Date().getTime() + Utility.randomString(7);


        request.put("body", body);
        request.put("out_trade_no", orderNo);
        request.put("device_info", "");
        request.put("fee_type", "CNY");
        request.put("total_fee", totalFee.toString());
        request.put("spbill_create_ip", "123.12.12.123");
        request.put("notify_url", "http://kuaisu.chengguokj.com/ajax/wxpay/payCallback");
        request.put("trade_type", "JSAPI");
        request.put("product_id", "12");
        request.put("openid", openId);

        try {
            Map<String, String> resp = wxpay.unifiedOrder(request);
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static Map<String, String> genPayParam(String pk, WXPayConstants.SignType signType) throws Exception {
        MyConfig config = new MyConfig();

        Map<String, String> data = new HashMap<String, String>();
        data.put("appId", config.getAppID());
        data.put("timeStamp", ((Long)(new Date().getTime() / 1000)).toString());
        data.put("nonceStr", WXPayUtil.generateNonceStr());
        data.put("package", pk);

        if (WXPayConstants.SignType.MD5.equals(signType)) {
            data.put(WXPayConstants.FIELD_SIGNTYPE, WXPayConstants.MD5);
        }
        else if (WXPayConstants.SignType.HMACSHA256.equals(signType)) {
            data.put(WXPayConstants.FIELD_SIGNTYPE, WXPayConstants.HMACSHA256);
        }
        data.put("paySign", WXPayUtil.generateSignature(data, config.getKey(), signType));

        return data;
    }

}
